<template>
  <div class="statistics">
    <ul class="total">
      <li v-for="(item, index) in countData" :key="index">
        <p class="total-title">{{ item.title }}</p>
        <div class="counts">
          <span class="count">{{ item.count }}</span>
          <img src="@/assets/images/quxiaojine.png" />
        </div>
      </li>
    </ul>

    <el-form class="third-form" inline :model="staticData.search" label-width="80px" @keyup.enter.prevent="onSearchClick">
      <el-form-item label="订单编号">
        <el-input class="third_input" v-model="staticData.search.orderCode" placeholder="请输入订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="采购商">
        <el-select v-model="staticData.search.customerId" filterable placeholder="请选择采购商" clearable>
          <el-option v-for="item in staticData.customerList" :label="item.customerName" :value="item.customerId" :key="item.customerId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" clearable>
        <el-date-picker class="date_input" v-model="staticData.search.createTime" type="daterange" format="YYYY/MM/DD" value-format="YYYY/MM/DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="onTimeChange" clearable></el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="staticData.search.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option v-for="(key, val) in consts.orderStatus" :label="key" :value="val" :key="key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结算方式">
        <el-select v-model="staticData.search.settleType" placeholder="请选择结算方式" clearable>
          <el-option v-for="(key, val) in consts.settleType" :label="key" :value="val" :key="key"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <div>
          <Button label="重置" @click="onResetFormClick" />
          <Button type="primary" label="搜索" @click="onSearchClick" />
        </div>
      </el-form-item>
    </el-form>

    <div class="outerTable">
      <el-dropdown>
        <Button type="primary" label="导出订单" />
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="onSelExportClick">导出选中订单</el-dropdown-item>
            <el-dropdown-item @click="onAllExportClick">导出全部订单</el-dropdown-item>
            <el-dropdown-item @click="onSearchExportClick">导出搜索订单</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-table ref="tableRef" class="boss_table" :height="tableHeight" :data="staticData.list" @selection-change="onSelectionChange" v-loading="loading">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="orderCode" width="180" label="订单编号" />
        <el-table-column prop="createTime" width="180" label="下单时间" />
        <el-table-column prop="orderPrice" label="订单金额/元" />
        <el-table-column prop="customerName" label="采购商" />
        <el-table-column prop="orderStatus" label="订单状态">
          <template #default="scope">
            {{ $formater.formaterOrderStatus(scope.row.orderStatus) }}
          </template>
        </el-table-column>
        <el-table-column prop="settleType" label="结算方式">
          <template #default="scope">
            {{ consts.settleType[scope.row.settleType] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <Link label="详情" @click="onToDetailClick(scope.row.orderId)" />
          </template>
        </el-table-column>
      </el-table>
      <Pager :page="staticData.search.page" :pageSizes="staticData.search.pageSizes" :total="staticData.total" :limit="staticData.search.limit" @current-change="onCurrentChange" @size-change="onSizeChange" />
    </div>
  </div>
</template>
<script setup>
import { reactive, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import api from '@/api'
import consts from '@/consts'
import formater from '@/formater'
import { calcTableHeight } from '@/assets/js/utils.js'
import Pager from '@/components/pager/index.vue'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'

const router = useRouter()

const { tableRef, tableHeight } = calcTableHeight()

const staticData = reactive({
  total: 0,
  totalOrder: {},
  list: [],
  // customerList: [],
  multipleSelection: [],
  search: {
    page: 1,
    limit: consts.Limit,
    pageSizes: consts.PageSize,
    orderCode: '',
    createTime: '',
    createTimeBegin: '',
    createTimeEnd: '',
    customerId: '',
    supplierId: '',
    goodsType: '',
    orderStatus: '',
    settleType: ''
  }
})
const loading = ref(false)

const countData = [
  {
    title: '订单总数',
    name: 'totalOrderNumber',
    count: '-'
  },
  {
    title: '订单金额',
    name: 'totalOrderPrice',
    count: '-'
  },
  {
    title: '售后订单',
    name: 'totalBackOrderNumber',
    count: '-'
  },
  {
    title: '退款金额',
    name: 'totalBackOrderPrice',
    count: '-'
  },
  {
    title: '实收金额',
    name: 'totalOrderRealPrice',
    count: '-'
  }
]

const customerData = async () => {
  let { data, err } = await api.get('/medinstrument/third/order/getCustomerList')
  if (err) {
    ElMessage.error(err)
  } else {
    staticData.customerList = data.customerVos
  }
}

const loadData = async () => {
  loading.value = true
  if (staticData.search.createTime) {
    staticData.search.createTimeBegin = staticData.search.createTime[0]
    staticData.search.createTimeEnd = staticData.search.createTime[1]
  }
  let params = Object.assign({}, staticData.search)
  delete params.createTime
  let { data, err } = await api.get('/medinstrument/third/statistics/orderStatistics', params)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    staticData.list = data.orderList
    staticData.total = data.count
    countData?.forEach((e) => {
      e.count = data?.[e.name]
    })
  }
}

const onTimeChange = (val) => {
  if (val) {
    staticData.search.createTimeBegin = val[0]
    staticData.search.createTimeEnd = val[1]
  } else {
    staticData.search.createTimeBegin = ''
    staticData.search.createTimeEnd = ''
  }
}

const onSearchClick = () => {
  staticData.search.page = 1
  loadData()
}

const onCurrentChange = (val) => {
  staticData.search.page = val
  loadData()
}

const onSizeChange = (val) => {
  staticData.search.limit = val
  loadData()
}

const onResetFormClick = () => {
  staticData.search = {}
}

const onSelectionChange = (val) => {
  staticData.multipleSelection = val
}

const onAllExportClick = () => {
  // if (staticData.multipleSelection.length !== staticData.list.length) {
  //   ElMessage.warning('导出全部订单前请先全选')
  //   return
  // }

  api.download('/medinstrument/third/exportExcel/exportOrder')
}

const onSelExportClick = () => {
  let orderIds = staticData.multipleSelection.map((e) => e.orderId).join(',')
  if (!orderIds) {
    ElMessage.warning('请选择订单')
    return
  }
  api.download(`/medinstrument/third/exportExcel/exportCheckOrder?orderIds=${orderIds}`)
}

const onSearchExportClick = () => {
  let orderIds = staticData.multipleSelection.map((e) => e.orderId).join(',')
  // let params = Object.assign({}, staticData.search)
  let params = JSON.parse(JSON.stringify(staticData.search))
  // if ((!params.createTime || !params.customerId || !params.orderCode || !params.orderStatus || !params.settleType) && !orderIds) {
  //   ElMessage.warning('请搜索订单并选择订单')
  //   return
  // }

  delete params.createTime
  delete params.pageSizes

  api.download('/medinstrument/third/exportExcel/exportOrder', params)
}

const onToDetailClick = (orderId) => {
  let { href } = router.resolve({
    path: `/order/detail/${orderId}`
  })
  window.open(href, '_blank')
}

onMounted(() => {
  loadData()
  customerData()
})
</script>
<style scoped lang="scss">
.statistics {
  padding: 10px 15px 0 10px;
  box-sizing: border-box;
  .total {
    height: 110px;
    display: flex;
    justify-content: space-between;

    li {
      flex: 1;
      height: 110px;
      background-color: #fff;
      border-radius: 4px;
      padding: 18px;
      box-sizing: border-box;
      margin-right: 10px;

      .total-title {
        height: 16px;
        line-height: 16px;
        font-size: 16px;
        color: var(--color-text);
        font-weight: 500;
      }

      .counts {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 30px;
        .count {
          display: inline-block;
          font-size: 28px;
          color: #0486fe;
          font-weight: 500;
          line-height: 28px;
        }

        img {
          width: 30px;
          height: 30px;
        }
      }
    }
    li:last-child {
      margin-right: 0;
    }
  }
}
</style>
